﻿
using Xacml.Core;
using System.Collections;
using System.Xml;

namespace Xacml.Core.Policy
{
  public class EnvironmentsElementReadWrite : TargetItemsBaseReadWrite
  {
    public override bool IsReadOnly
    {
      get
      {
        return false;
      }
    }

    public EnvironmentsElementReadWrite(bool anyItem, TargetItemCollectionReadWrite items, XacmlVersion version)
      : base(anyItem, items, version)
    {
    }

    public EnvironmentsElementReadWrite(XmlReader reader, XacmlVersion version)
      : base(reader, "Environments", "AnyEnvironment", "Environment", version)
    {
    }

    protected override TargetItemBaseReadWrite CreateTargetItem(XmlReader reader)
    {
      return (TargetItemBaseReadWrite) new EnvironmentElementReadWrite(reader, this.SchemaVersion);
    }

    public void WriteDocument(XmlWriter writer)
    {
      writer.WriteStartElement("Environments");
      if (this.IsAny)
      {
        writer.WriteElementString("AnyEnvironment", string.Empty);
      }
      else
      {
        foreach (EnvironmentElementReadWrite elementReadWrite1 in (CollectionBase) this.ItemsList)
        {
          writer.WriteStartElement("Environment");
          foreach (EnvironmentMatchElementReadWrite elementReadWrite2 in (CollectionBase) elementReadWrite1.Match)
          {
            writer.WriteStartElement("EnvironmentMatch");
            writer.WriteAttributeString("MatchId", elementReadWrite2.MatchId);
            writer.WriteStartElement("AttributeValue");
            writer.WriteAttributeString("DataType", elementReadWrite2.AttributeValue.DataType);
            writer.WriteString(elementReadWrite2.AttributeValue.Value);
            writer.WriteEndElement();
            if (elementReadWrite2.AttributeReference is EnvironmentAttributeDesignatorElement)
              elementReadWrite2.AttributeReference.WriteDocument(writer);
            else if (elementReadWrite2.AttributeReference is AttributeSelectorElement)
              elementReadWrite2.AttributeReference.WriteDocument(writer);
            writer.WriteEndElement();
          }
          writer.WriteEndElement();
        }
      }
      writer.WriteEndElement();
    }
  }
}
